import React, { Component } from 'react';
import { Input, Space, List, Avatar, Image } from 'antd';

import { SearchOutlined, FolderOutlined, FileOutlined } from '@ant-design/icons';

import styles from './index.less';



class Index extends Component {

    constructor(props) {
        super(props);
        this.handleKeyDown = this.handleKeyDown.bind(this)
        this.state = {
            slogan: "",
            keyword: "",
            preSearch: "",
            searchResult: [],
            cursor: 0,
            iconType: "default",
            relativeCursor: 1,
            subInput: null,
            subInputDetail: null,
        };

    }



    componentDidMount() {
        this.initSlogan()
    }


    initSlogan = () => {
        const slogan = window.appBridge.userConfig.getSlogan()
        this.setState({ slogan: slogan })
    }

    onSearch = (e) => {
        const keyword = e.target.value
        this.setState({ keyword: keyword })
        const payload = this.composeSearchRequest("string", null, keyword)
        const result = window.appBridge.baseService.search(payload)
        this.setState({ preSearch: result?.preSearch, searchResult: result?.resultList })
        this.resetCursor()

    }

    composeSearchRequest = (type: string, subInput: string | null, input: string) => {
        return {
            type: type,
            subInput: subInput,
            input: input
        }

    }



    inputOnDrop = (e) => {
        e.preventDefault()
        const files = e.dataTransfer.files
        if (files && files.length > 0) {
            const path = files[0].path
            const lastName = path.split("/").pop()
            let iconType = "folder"
            if (lastName.indexOf(".") > 0) {
                iconType = "file"
            }
            this.setState({ iconType: iconType, subInput: lastName, subInputDetail: { path: path } })
            const payload = this.composeSearchRequest(iconType, lastName, path)
            const result = window.appBridge.baseService.search(payload)
            this.setState({ preSearch: result?.preSearch, searchResult: result?.resultList })
            this.resetCursor()
        }
    }

    runByListItem = (plugin) => {
        const payload = {
            ...plugin,
            input: this.state.keyword,
            subInput: this.state.subInput,
            subInputDetail: this.state.subInputDetail,
        }
        const result = window.appBridge.baseService.runPlugin(payload)
        console.info("runByListItemresult", result)
        if (result != undefined) {
            this.setState({ preSearch: result?.preSearch, searchResult: result?.resultList })
        } else {
            this.resetSearchList()
        }
        this.resetCursor()
    }

    resetCursor = () => {
        this.setState({ cursor: 0, relativeCursor: 1 })
    }

    resetSearchList = () => {
        this.setState({ searchResult: [] })
    }

    renderIcon = () => {
        if (this.state.iconType == "default") {
            return (<SearchOutlined style={{ fontSize: 24, color: '#6b6c6c' }} />)
        } else if (this.state.iconType == "folder") {
            return (<div className={styles.folderStyle} ><FolderOutlined style={{ fontSize: 18, color: '#6b6c6c' }} />{this.state.subInput}</div>)
        } else if (this.state.iconType == "file") {
            return (<div className={styles.folderStyle} ><FileOutlined style={{ fontSize: 18, color: '#6b6c6c' }} />{this.state.subInput}</div>)
        }


    }

    handleKeyDown = (e) => {
        const { cursor, searchResult, relativeCursor } = this.state
        console.info("e.keyCode", e.keyCode)
        if (e.keyCode === 38 && cursor >= 0) {
            // 向上滚动
            this.setState(prevState => {
                const theCursor = cursor == 0 ? searchResult.length - 1 : prevState.cursor - 1


                // 设置可视范围的序号
                let theRelativeCursor = relativeCursor
                if (relativeCursor > 1) {
                    theRelativeCursor = relativeCursor - 1
                }
                if (theRelativeCursor > 9) {
                    theRelativeCursor = 9
                }

                // 设置滚动
                let searchList = document.querySelector("#searchList")
                if (theRelativeCursor == 1) {
                    searchList?.scrollTo(0, theCursor * 60)
                }
                console.info("searchResult.length up", searchResult.length, theCursor, cursor, theRelativeCursor)


                return ({ cursor: theCursor, relativeCursor: theRelativeCursor })
            })
        } else if (e.keyCode === 40 && cursor <= searchResult.length - 1) {
            // 向下滚动
            this.setState(prevState => {
                const theCursor = cursor == searchResult.length - 1 ? 0 : prevState.cursor + 1


                // 设置可视范围的序号
                let theRelativeCursor = theCursor + 1
                if (theCursor > 8) {
                    theRelativeCursor = 9
                }

                // 设置滚动
                let searchList = document.querySelector("#searchList")
                if (theRelativeCursor == 9) {
                    searchList?.scrollTo(0, (theCursor - 8) * 60)
                } else if (theCursor == 0) {
                    searchList?.scrollTo(0, 0)
                }


                console.info("searchResult.length down", searchResult.length, theCursor, cursor, theRelativeCursor)


                return ({ cursor: theCursor, relativeCursor: theRelativeCursor })
            })
        } else if (e.keyCode === 13) {
            // 回车执行插件
            const thePlugin = this.state.searchResult[this.state.cursor]
            this.runByListItem(thePlugin)
        } else if (e.keyCode === 8) {
            console.info("正在执行删除动作")
            if (this.state.subInput != null && this.state.keyword == "") {
                this.resetSubInput()

            }

        } else if (e.keyCode === 27) {
            console.info("正在执行ESC动作")
            console.info("正在执行ESC 退出隐藏动作", this.state.keyword)

            if (this.state.keyword == "") {
                window.appBridge.baseService.switchHide()
            }
        }
    }


    resetSubInput = () => {
        this.setState({ subInput: null, iconType: "default" })
    }

    renderWebView = () => {

        return (<webview
            id="webview"
            nodeintegration
            nodeintegrationinsubframes
            allowpopups
            disablewebsecurity
            plugins

            src="file:///Users/liuyongliang/Desktop/testPlugin/index.html"
            preload="file:///Users/liuyongliang/Desktop/testPlugin/preload.js"
        ></webview>)

    }

    render() {
        var webview = document.getElementById("webview");

        var loadstart = () => {
            console.log("loadstart");
        }
        var loadstop = () => {
            console.log("loadstop");
        }
        if (webview) {
            webview.addEventListener("did-start-loading", loadstart);
            webview.addEventListener("did-stop-loading", loadstop);
            webview.addEventListener('dom-ready', () => {
                webview.openDevTools()//webview加载完成，可以处理一些事件了
            })
        }


        return (
            <div>

                <Input
                    prefix={this.renderIcon()}
                    autoComplete="off"
                    autoCapitalize="off"
                    autoCorrect="off"
                    placeholder={this.state.slogan}
                    onChange={this.onSearch}
                    bordered={false}
                    size="large"
                    autoFocus="autofocus"
                    onChange={this.onSearch}
                    className={styles.mainInput}
                    onDrop={this.inputOnDrop}
                    onKeyDown={this.handleKeyDown}
                />
                {/* {this.renderWebView()} */}

                {this.state.searchResult.length > 0 ? (

                    <List
                        // itemLayout="horizontal"
                        className={styles.listContain}
                        dataSource={this.state.searchResult}
                        id="searchList"
                        renderItem={(item, i) => (
                            <List.Item
                                key={i}
                                className={this.state.cursor === i ? styles.listStyle4Selected : styles.listStyle}
                                onClick={() => this.runByListItem(item)}
                            >
                                <List.Item.Meta
                                    avatar={
                                        <div>
                                            <div className={styles.imgbox} data-text="1">
                                                <Image className={styles.listIcon} src={item.icon} />
                                            </div>


                                        </div>


                                    }
                                    title={<div >{item.name}</div>}
                                    description={item.desc}
                                />
                            </List.Item>
                        )
                        }
                    />
                ) : (<div />)}


            </div >
        );
    }
}


export default Index;